package com.tanhua.autoconfig.template;

import cn.hutool.core.collection.CollUtil;
import com.easemob.im.server.EMProperties;
import com.easemob.im.server.EMService;
import com.easemob.im.server.model.EMTextMessage;

import lombok.extern.slf4j.Slf4j;

import java.util.Set;

@Slf4j
public class HuanXinTemplate {

    private String appkey= "1142220224135832#tanhua-137";
    private String clientId= "YXA6Nl7XxLc2RlGd1as_A-GV1w";
    private String clientSecret= "YXA6iKIiWy7LPLzW6nSUkg8IqYw6sU0";

    private EMService emService;


    public HuanXinTemplate() {
        EMProperties emProperties = EMProperties.builder()
                .setAppkey(appkey)
                .setClientId(clientId)
                .setClientSecret(clientSecret)
                .build();
        emService = new EMService(emProperties);
    }

    //创建环信用户
    public Boolean createUser(String username, String password) {
        try {
            //创建环信用户
            emService.user().create(username.toLowerCase(), password)
                    .block();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("创建环信用户失败~");
        }
        return false;
    }

    //添加联系人
    public Boolean addContact(String username, String contact) {
        try {
            //创建环信用户
            emService.contact().add(username, contact)
                    .block();
            return true;
        } catch (Exception e) {
            log.error("添加联系人失败~");
        }
        return false;
    }

    //删除联系人
    public Boolean deleteContact(String username, String contact) {
        try {
            //创建环信用户
            emService.contact().remove(username, contact)
                    .block();
            return true;
        } catch (Exception e) {
            log.error("删除联系人失败~");
        }
        return false;
    }

    //发送消息
    public Boolean sendMsg(String username, String content) {
        try {
            //接收人用户列表
            Set<String> set = CollUtil.newHashSet(username);
            //文本消息
            EMTextMessage message = new EMTextMessage().text(content);
            //发送消息  from：admin是管理员发送
            emService.message().send("admin", "users",
                    set, message, null).block();
            return true;
        } catch (Exception e) {
            log.error("删除联系人失败~");
        }
        return false;
    }
}
